<?php

declare(strict_types=1);


namespace app\common\model;

use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class GmTgczlogsTqk extends Model
{
    use SoftDelete;
    protected $deleteTime = "delete_time";
    // 获取列表
    public static function getList()
    {
        $where = [];
        $limit = input('get.limit');
        $where[] = ["status", "=", "1"];
        //按查找
        if ($serverid = input("serverid")) {
            $where[] = ["serverid", "=", $serverid];
        }
        //按查找
        if ($actorname = input("actorname")) {
            $where[] = ["actorname", "like", "%" . $actorname . "%"];
        }
        //按查找
        if ($actoraccount = input("actoraccount")) {
            $where[] = ["actoraccount", "like", "%" . $actoraccount . "%"];
        }
        //按充值类型查找
        if ($cztype = input("cztype")) {
            $where[] = ["cztype", "=", $cztype];
        }
        //按特权卡类型 0. 50   1. 100   2. 300查找
        if ($tqktype = input("tqktype")) {
            $where[] = ["tqktype", "=", $tqktype];
        }
        //select serverid,actorname,ddcode,tqktype,sum(symonth) symonth from gm_tgczlogs_tqk where  `status`=1  GROUP BY serverid,actorname,tqktype;
        $list = self::order('id', 'desc')
            ->field('id,serverid,actorname,ddcode,tqktype,status,actoraccount,cztype,cztime,remake,actorid,sum(symonth) symonth')
            ->group('serverid,actorname,tqktype')
            ->where($where)
            ->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }


    // 获取用户下拉
    public static function getSelect()
    {
        return Db::table('gmpre.admin_admin')->order('id')->field('id,username,rlink,nickname')->select(); // 直接返回结果数组，不要包装在 ['code'=>0,'data'=>...] 中
    }

    // 获取服务器列表下拉
    public static function getServerLsSelect()
    {
        return Db::table('h5.h5_server')->order('sid')->field('id,sid,name')->select();
    }

    public static function getqueryList($account, $serverid){

        $query ="select serverid,actorname,ddcode,tqktype,sum(symonth) symonth from gm_tgczlogs_tqk where  `status`=1  and actorname='{$account}' and serverid='{$serverid}'  
        GROUP BY serverid,actorname,tqktype;";
        return  Db::query( $query);
        
    }



    // 累加玩家RMB 这里注意。只针对特权卡 因为修改了金额*1000
    public static function accrualPlayerRmb($actorname, $serverid, $rmb)
    {
        $newserverid = self::getDBName($serverid);
        $newrmb = (float)$rmb * 1000;
        //注意！！！！  注意！！！！   这里是先查后加，rmb的添加必须在修改之前test
        self::addPlayerRmblog($serverid, $actorname, '+' . $newrmb, "后台添加特权卡发放");
        $sql = "UPDATE $newserverid.globaluser SET rmb=rmb+$newrmb WHERE account='$actorname';";
        Db::execute($sql);
    }


    // 发送指定特权卡物品邮件
    public static function sendTQKEmail($serverid, $actorid, $type, $num, $account)
    {
        $newserverid = self::getDBName($serverid);
        // 初始化默认的数量
        $skinQty = $num * 1;
        $invitationQty = $num * 1;

        if ($type == "998") {
            $stoneQty = $num * 150000;
            $sql = "INSERT INTO $newserverid.gmcmd (serverid,cmdid,cmd,param1,param2,param3,param4,param5) 
                VALUES ('$serverid','1','sendMail','开通" . $type . "超级卡物品发放', '超级月卡皮肤1*$skinQty,超级月卡1邀请函*$invitationQty,始皇石*$stoneQty','$actorid','1,108761,$skinQty;1,368121,$invitationQty;1,1095000,$stoneQty','');";
        } else if ($type == "1998") {
            $stoneQty = $num * 300000;
            $sql = "INSERT INTO $newserverid.gmcmd (serverid,cmdid,cmd,param1,param2,param3,param4,param5) 
                VALUES ('$serverid','1','sendMail','开通" . $type . "超级卡物品发放', '超级月卡皮肤2*$skinQty,超级月卡2邀请函*$invitationQty,始皇石*$stoneQty','$actorid','1,108760,$skinQty;1,368122,$invitationQty;1,1095000,$stoneQty','');";
        } else if ($type == "4998") {
            $stoneQty = $num * 550000;
            $sql = "INSERT INTO $newserverid.gmcmd (serverid,cmdid,cmd,param1,param2,param3,param4,param5) 
                VALUES ('$serverid','1','sendMail','开通" . $type . "超级卡物品发放', '超级月卡皮肤3*$skinQty,超级月卡3邀请函*$invitationQty,始皇石*$stoneQty','$actorid','1,108758,$skinQty;1,368123,$invitationQty;1,1095000,$stoneQty','');";
        }

        Db::execute($sql);
    }

    //检测是否有六卡  如果有  则触发大月卡奖励
    public static function Jianc($actorid, $serverid)
    {
        $address = env('APP_DEBUG') ? config('web')['developmentServer'] : config('web')['productionServer'];
        //---------------------------------   注意url  --------------------------------------------------------------
        $url = 'http://' . $address . '/api/Task6.php?pwd=iMdWZ5enYJxmwpFN&actorid=' . $actorid . '&serverid=' . $serverid;
        // 初始化 cURL 会话
        $ch = curl_init($url);
        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 设置为 true，以便获取响应
        // 执行 cURL 请求并获取响应
        $response = curl_exec($ch);
    }


    // 根据区服和账号获取角色名
    public static function getqueryuname($actorname, $serverid)
    {
        $where = [];
        $where[] =  ['accountname', '=', $actorname];
        $newserverid = self::getDBName($serverid);
        return Db::table($newserverid . '.actors')->field('actorid,actorname')->where($where)->select();
    }

    // 添加一条玩家RMB修改记录   注意！！！！  注意！！！！   这里是先查后加，rmb的添加必须在修改之前
    public static function  addPlayerRmblog($serverid, $account, $consrmb, $itemid)
    {
        $newserverid = self::getDBName($serverid);

        $sql = "select rmb from $newserverid.globaluser where account='$account';";
        $row =  Db::query($sql);
        $oldrmb = $row[0]['rmb'];

        if (substr($consrmb, 0, 1) === "+") {
            substr($consrmb, 1);
            $nowrmb = (float)$oldrmb + (float)$consrmb;
        } else {
            $nowrmb = (float)$oldrmb - (float)$consrmb;
        }

        $sql1 = "INSERT INTO `gmpre`.`gm_conslog`(`serverid`, `qufu`, `account`, `oldrmb`, `nowrmb`, `consrmb`, `itemid`, `xftime`) 
         VALUES ('$serverid', '$newserverid', '$account', '$oldrmb', '$nowrmb', '$consrmb', '$itemid', now());";

        Db::execute($sql1);
    }



    // 角色转职
    public static function getRole2Job($actorname, $serverid, $Job)
    {
        $newserverid = self::getDBName($serverid);
        $sql = "UPDATE $newserverid.actors SET job=$Job WHERE accountname='$actorname';";
        Db::execute($sql);
    }

    // 修改服务器状态
    public static function getUpdateServerStatus($tag, $status, $serverid)
    {
        $sql = '';
        //全部
        if ($tag == '1') {
            $sql = "UPDATE h5.actors SET status=$status;";
        }
        //单个
        if ($tag == '2') {
            $sql = "UPDATE h5.actors SET status=$status  WHERE id=$serverid;";
        }
        Db::execute($sql);
    }

    // 发送邮件 单文本内容
    public static function SendEmail($serverid, $mailHead, $mailContext, $actorid)
    {
        $newserverid = self::getDBName($serverid);
        $sql = "INSERT INTO $newserverid.gmcmd (serverid,cmdid,cmd,param1,param2,param3,param4,param5) 
        VALUES ('{$serverid}','1','sendMail','{$mailHead}', '{$mailContext}','{$actorid}','','')";
        Db::execute($sql);

        // self::Jianc($actorid,$serverid);
    }

    // 发送邮件 单文本内容s
    public static function SendZadanNum($serverid, $actorid, $addCoin)
    {
        $sql = "update blackbox_playerinfo set cjcoin=cjcoin+$addCoin where actorid='{$actorid}' and qufu='{$serverid}';";
        Db::execute($sql);

        $sql1 = "INSERT INTO `gmpre`.`gm_conslog`(`serverid`, `qufu`, `account`, `oldrmb`, `nowrmb`, `consrmb`, `itemid`, `xftime`) 
         VALUES ('$serverid', '$serverid', '$actorid', '', '', '$addCoin', '后台添加盲盒金特权卡', now());";

        Db::execute($sql1);
    }

    // 发送邮件 发送物品 
    public static function SendEmailGoods($serverids, $mailHead, $mailContext, $goods, $sendType)
    {
        if ($sendType == '1') {
            return self::SendEmailGoodsOnly($serverids, $mailHead, $mailContext, $goods);
        }

        if ($sendType == '2') {
            $data = explode(';', $serverids);

            foreach ($data as $item) {
                if (empty($item)) {
                    continue;
                } // 跳过空数据项 
                self::SendEmailGoodsOnly($item, $mailHead, $mailContext, $goods);
            }
        }

        if ($sendType == '3') {
            return self::SendEmailGoodsGlobal($serverids, $mailHead, $mailContext, $goods);
        }

        if ($sendType == '4') {
            $array = json_decode($serverids);

            $msg = '';
            foreach ($array as $value) {
                $msg .=  self::SendEmailGoodsGlobal($value, $mailHead, $mailContext, $goods);
            }
            return $msg;
        }
    }

    //单人邮件
    public static function SendEmailGoodsOnly($inputdata, $mailHead, $mailContext, $goods)
    {
        $data = explode(',', $inputdata);
        $account = $data[0];
        $serverid = $data[1];
        $actorid = explode('&', $data[2])[0];
        $job = explode('&', $data[2])[1];

        $semicolonSeparated = explode(';', $goods);
        $imgs = ''; //显示物品数量
        $currImgs = ''; //实际执行的值
        $index = 0; // 用于跟踪索引
        $newserverid = self::getDBName($serverid);

        foreach ($semicolonSeparated as $segment) {
            if (empty($segment)) {
                continue;
            } // 跳过空数据项 
            $commaSeparated = explode('|', $segment);
            $id = $commaSeparated[0];
            $name = $commaSeparated[1];
            $num = $commaSeparated[2];

            if ($id == 'ptb') {
                //平台币相关逻辑
                $sql1 = "UPDATE $newserverid.globaluser SET rmb=rmb+$num WHERE account='{$account}';";
            } else {
                if (strpos($name, ',')) {
                    $name = explode(',', $name)[intval($job) - 1];
                }
                $name = trim($name, "[ '']");

                if ($index > 0) {
                    // 这不是第一个索引
                    $currImgs .= ";1,{$id},{$num}";
                } else {
                    $currImgs .= "1,{$id},{$num}";
                }
                $index++; // 增加索引
            }
            $imgs .= "\n【{$name}*{$num}】";
        }

        $sql2 = "INSERT INTO $newserverid.gmcmd (serverid,cmdid,cmd,param1,param2,param3,param4,param5) 
        VALUES ('{$serverid}','1','sendMail','{$mailHead}', '{$mailContext}{$imgs}','{$actorid}','{$currImgs}','');";

        // 开启事务
        Db::startTrans();

        try {
            // 执行第一条 SQL 语句
            Db::execute($sql1);
            // 执行第二条 SQL 语句
            Db::execute($sql2);
            // 提交事务
            Db::commit();
            return "邮件发送成功！";
        } catch (\Exception $e) {
            // 发生异常，回滚事务
            Db::rollback();
            return "邮件发送失败！" . $e;
        }
    }

    //全局邮件
    public static function SendEmailGoodsGlobal($serverid, $mailHead, $mailContext, $goods)
    {

        $semicolonSeparated = explode(';', $goods);

        $index = 0; // 用于跟踪索引
        $newserverid = self::getDBName($serverid);
        $currImgs = ''; //实际执行的值

        foreach ($semicolonSeparated as $segment) {
            if (empty($segment)) {
                continue;
            } // 跳过空数据项
            $commaSeparated = explode('|', $segment);
            $id = $commaSeparated[0];
            $num = $commaSeparated[2];

            if ($id == 'ptb') {
                //平台币相关逻辑
                $sql1 = "UPDATE $newserverid.globaluser SET rmb=rmb+$num;";
            } else {
                if ($index > 0) {
                    // 这不是第一个索引
                    $currImgs .= ";1,{$id},{$num}";
                } else {
                    $currImgs .= "1,{$id},{$num}";
                }
                $index++; // 增加索引
            }
        }


        $sql2 = "INSERT INTO $newserverid.gmcmd (serverid,cmdid,cmd,param1,param2,param3,param4,param5) 
        VALUES ('{$serverid}','1','sendGlobalMail','{$mailHead}', '{$mailContext}','{$currImgs}','','');";

        try {
            Db::execute($sql1);
        } catch (\Throwable $th) {
            //throw $th;
        }
        try {
            Db::execute($sql2);
        } catch (\Throwable $th) {
            //throw $th;
        }


        // 开启事务
        // Db::startTrans();

        // try {

        //     // 提交事务
        //     Db::commit();
        //     return "邮件发送成功！";
        // } catch (\Exception $e) {
        //     // 发生异常，回滚事务
        //     // Db::rollback();
        //     // return "邮件发送失败！";
        //     // return "邮件发送失败！".$e;
        // }

    }

    // 修改玩家密码
    public static function MoPalyerPwd($actorname, $password)
    {
        $newpassword = md5(trim($password));

        $sql1 = "UPDATE `h5`.`account` SET `pass` = '$newpassword' WHERE `account` = '$actorname';";
        Db::execute($sql1);


        $servers = self::getDBNameAll();

        $sql2 = '';
        foreach ($servers as $server) {
            $sql2 = "UPDATE $server.`globaluser` SET `passwd` = '$newpassword' WHERE `account` = '$actorname';";
            Db::execute($sql2);
        }
    }

    // 修改玩家密码
    public static function MoPalyerNweUser($actorname, $adminuser)
    {
        $sql = "UPDATE  gm_tglogs SET acode='$adminuser' WHERE baccount='$actorname';";
        Db::execute($sql);
    }

    // 修改区服名称
    public static function MoServerName($id, $servername)
    {
        $newServername = $servername . '【S' . $id . '】';
        $sql = "UPDATE  h5.h5_server SET name='$newServername' WHERE id=$id;";
        Db::execute($sql);
    }

    // 获取数据库名称 传入$serverid
    public static function getDBName($serverid)
    {
        $newserverid = 'h5_cq_';
        // 使用正则表达式匹配并获取有效的字符
        $integerValue = intval($serverid) - 1000;
        // 如果有匹配到有效字符，则返回匹配结果，否则返回 "0"
        $trimmedString = $integerValue < 0 ? "0" : strval($integerValue);
        if (env('APP_DEBUG')) {
            $newserverid .= '00' . $trimmedString;
        } else {
            $newserverid .= '' . $trimmedString;
        }

        return $newserverid;
    }


    // 获取 所有 数据库名称
    public static function getDBNameAll()
    {

        $data = [];
        $sql = "select distinct sid from h5.h5_server where sid<'1999';";
        $rows = Db::query($sql);

        foreach ($rows as $row) {
            // 如果$row确实是一个关联数组，且包含名为'sid'的键
            if (isset($row['sid'])) {
                // 将'sid'的值添加到$data数组
                $newserverid = 'h5_cq_';
                // 使用正则表达式匹配并获取有效的字符
                $integerValue = intval($row['sid']) - 1000;
                // 如果有匹配到有效字符，则返回匹配结果，否则返回 "0"
                $trimmedString = $integerValue < 0 ? "0" : strval($integerValue);
                if (env('APP_DEBUG')) {
                    if (strval($trimmedString) < 10) {
                        $newserverid .= '00' . $trimmedString;
                    } else if (strval($trimmedString) < 100) {
                        $newserverid .= '0' . $trimmedString;
                    } else {
                        $newserverid .= $trimmedString;
                    }
                } else {
                    $newserverid .= '' . $trimmedString;
                }
                $data[] = $newserverid;
            }
        }

        return $data;
    }
}
